from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse, HttpResponse
# Create your views here.
import string
from django.core.mail import send_mail
import random
from .models import VerificationCode
from .forms import RegistrerForm, LoginForm
from django.views.decorators.http import require_http_methods
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.models import User

User = get_user_model()


def do_login(request):
    if request.method == 'POST':
        lognForm = LoginForm(request.POST)
        if lognForm.is_valid():
            username = lognForm.cleaned_data.get('username')
            password = lognForm.cleaned_data.get('password')
            remember = lognForm.cleaned_data.get('remember')
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                return render(request, 'login.html', context={"msg": "账号或者密码错误!"})
        if user and user.check_password(password):
            login(request, user)
            if not remember:
                request.session.set_expiry(0)
                return redirect('/')
            return redirect(reverse('blog:blog_list'))
        else:
            return render(request, 'login.html', context={"msg": "账号或者密码错误!"})
    return render(request, 'login.html')


@require_http_methods(['GET', 'POST'])
def registry(request):
    if request.method == 'GET':
        return render(request, 'registry.html')
    else:
        data = RegistrerForm(request.POST)
        if data.is_valid():
            username = data.cleaned_data['username']
            password = data.cleaned_data['password']
            email = data.cleaned_data['email']
            User.objects.create_user(email=email, password=password, username=username)
            return redirect(reverse("zauth:login"))
        else:
            print(data.errors)
            return render(request, 'registry.html', context={'formData': data.errors})


def send_email(request):
    email = request.GET.get("email")
    if email == "" or email == None:
        return JsonResponse({'code': 400, 'msg': '邮箱号码不能为空！'})
    verity_code = "".join(random.sample(string.digits, 4))
    send_mail('我的主题', verity_code, None, [email])
    VerificationCode.objects.update_or_create(email=email, defaults={'code': verity_code})
    return JsonResponse({'code': 200, 'msg': '发送邮箱成功!'})


def login_out(request):
    logout(request)
    return redirect("/")
